package com.stu.designpattern;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.io.*;

// ==================== 单例模式实现 ====================

/**
 * 饿汉式单例：类加载时就创建实例
 * 优点：线程安全，简单
 * 缺点：可能造成内存浪费
 */
class EagerSingleton {
    // 在类加载时就创建实例
    private static final EagerSingleton INSTANCE = new EagerSingleton();
    
    // 私有构造器
    private EagerSingleton() {
        System.out.println("EagerSingleton实例创建");
    }
    
    // 提供全局访问点
    public static EagerSingleton getInstance() {
        return INSTANCE;
    }
    
    public void doSomething() {
        System.out.println("EagerSingleton执行操作");
    }
}

/**
 * 懒汉式单例：第一次使用时才创建实例
 * 优点：延迟加载
 * 缺点：需要考虑线程安全
 */
class LazySingleton {
    private static LazySingleton instance;
    
    private LazySingleton() {
        System.out.println("LazySingleton实例创建");
    }
    
    // 同步方法保证线程安全
    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
    
    public void doSomething() {
        System.out.println("LazySingleton执行操作");
    }
}

/**
 * 双重检查锁单例：性能优化的懒汉式
 * 优点：延迟加载，性能好
 * 缺点：代码复杂
 */
class DoubleCheckSingleton {
    // volatile保证可见性和禁止指令重排
    private static volatile DoubleCheckSingleton instance;
    
    private DoubleCheckSingleton() {
        System.out.println("DoubleCheckSingleton实例创建");
    }
    
    public static DoubleCheckSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckSingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckSingleton();
                }
            }
        }
        return instance;
    }
    
    public void doSomething() {
        System.out.println("DoubleCheckSingleton执行操作");
    }
}

/**
 * 枚举单例：最佳实现方式
 * 优点：线程安全，防止反射和序列化攻击，简洁
 * 缺点：不能延迟加载
 */
enum EnumSingleton {
    INSTANCE;
    
    EnumSingleton() {
        System.out.println("EnumSingleton实例创建");
    }
    
    public void doSomething() {
        System.out.println("EnumSingleton执行操作");
    }
}

// ==================== 工厂模式实现 ====================

/**
 * 形状接口
 */
interface Shape {
    void draw();
}

/**
 * 具体形状实现
 */
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("绘制圆形");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("绘制矩形");
    }
}

class Triangle implements Shape {
    @Override
    public void draw() {
        System.out.println("绘制三角形");
    }
}

/**
 * 简单工厂：一个工厂类创建所有产品
 */
class ShapeFactory {
    public static Shape createShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        
        switch (shapeType.toUpperCase()) {
            case "CIRCLE":
                return new Circle();
            case "RECTANGLE":
                return new Rectangle();
            case "TRIANGLE":
                return new Triangle();
            default:
                throw new IllegalArgumentException("未知的形状类型：" + shapeType);
        }
    }
}

/**
 * 动物接口
 */
interface Animal {
    void makeSound();
}

/**
 * 具体动物实现
 */
class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("狗：汪汪汪");
    }
}

class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("猫：喵喵喵");
    }
}

/**
 * 抽象工厂：每个产品有对应的工厂
 */
abstract class AnimalFactory {
    public abstract Animal createAnimal();
}

/**
 * 具体工厂实现
 */
class DogFactory extends AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Dog();
    }
}

class CatFactory extends AnimalFactory {
    @Override
    public Animal createAnimal() {
        return new Cat();
    }
}

/**
 * GUI组件接口
 */
interface Button {
    void click();
}

interface TextField {
    void input(String text);
}

/**
 * Windows风格组件
 */
class WindowsButton implements Button {
    @Override
    public void click() {
        System.out.println("Windows按钮被点击");
    }
}

class WindowsTextField implements TextField {
    @Override
    public void input(String text) {
        System.out.println("Windows文本框输入：" + text);
    }
}

/**
 * Mac风格组件
 */
class MacButton implements Button {
    @Override
    public void click() {
        System.out.println("Mac按钮被点击");
    }
}

class MacTextField implements TextField {
    @Override
    public void input(String text) {
        System.out.println("Mac文本框输入：" + text);
    }
}

/**
 * 抽象工厂：创建产品族
 */
abstract class GUIFactory {
    public abstract Button createButton();
    public abstract TextField createTextField();
}

/**
 * 具体工厂实现
 */
class WindowsFactory extends GUIFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }
    
    @Override
    public TextField createTextField() {
        return new WindowsTextField();
    }
}

class MacFactory extends GUIFactory {
    @Override
    public Button createButton() {
        return new MacButton();
    }
    
    @Override
    public TextField createTextField() {
        return new MacTextField();
    }
}

// ==================== 建造者模式实现 ====================

/**
 * 计算机产品类
 */
class Computer {
    private String cpu;
    private String memory;
    private String storage;
    private String graphics;
    private String motherboard;
    
    // 包级私有构造器，只能通过建造者创建
    Computer(ComputerBuilder builder) {
        this.cpu = builder.cpu;
        this.memory = builder.memory;
        this.storage = builder.storage;
        this.graphics = builder.graphics;
        this.motherboard = builder.motherboard;
    }
    
    @Override
    public String toString() {
        return "Computer{" +
                "cpu='" + cpu + '\'' +
                ", memory='" + memory + '\'' +
                ", storage='" + storage + '\'' +
                ", graphics='" + graphics + '\'' +
                ", motherboard='" + motherboard + '\'' +
                '}';
    }
    
    // Getter方法
    public String getCpu() { return cpu; }
    public String getMemory() { return memory; }
    public String getStorage() { return storage; }
    public String getGraphics() { return graphics; }
    public String getMotherboard() { return motherboard; }
}

/**
 * 抽象建造者
 */
abstract class ComputerBuilder {
    protected String cpu;
    protected String memory;
    protected String storage;
    protected String graphics;
    protected String motherboard;
    
    public abstract ComputerBuilder buildCPU();
    public abstract ComputerBuilder buildMemory();
    public abstract ComputerBuilder buildStorage();
    public abstract ComputerBuilder buildGraphics();
    public abstract ComputerBuilder buildMotherboard();
    
    public Computer build() {
        return new Computer(this);
    }
}

/**
 * 游戏电脑建造者
 */
class GamingComputerBuilder extends ComputerBuilder {
    @Override
    public ComputerBuilder buildCPU() {
        this.cpu = "Intel i9-12900K";
        return this;
    }
    
    @Override
    public ComputerBuilder buildMemory() {
        this.memory = "32GB DDR4";
        return this;
    }
    
    @Override
    public ComputerBuilder buildStorage() {
        this.storage = "1TB NVMe SSD";
        return this;
    }
    
    @Override
    public ComputerBuilder buildGraphics() {
        this.graphics = "NVIDIA RTX 4080";
        return this;
    }
    
    @Override
    public ComputerBuilder buildMotherboard() {
        this.motherboard = "ASUS ROG Strix Z690";
        return this;
    }
}

/**
 * 办公电脑建造者
 */
class OfficeComputerBuilder extends ComputerBuilder {
    @Override
    public ComputerBuilder buildCPU() {
        this.cpu = "Intel i5-12400";
        return this;
    }
    
    @Override
    public ComputerBuilder buildMemory() {
        this.memory = "16GB DDR4";
        return this;
    }
    
    @Override
    public ComputerBuilder buildStorage() {
        this.storage = "512GB SSD";
        return this;
    }
    
    @Override
    public ComputerBuilder buildGraphics() {
        this.graphics = "集成显卡";
        return this;
    }
    
    @Override
    public ComputerBuilder buildMotherboard() {
        this.motherboard = "华硕 B660M";
        return this;
    }
}

/**
 * 指挥者类
 */
class ComputerDirector {
    public Computer construct(ComputerBuilder builder) {
        return builder
                .buildCPU()
                .buildMemory()
                .buildStorage()
                .buildGraphics()
                .buildMotherboard()
                .build();
    }
}

/**
 * 链式建造者模式示例
 */
class Person {
    private final String name;
    private final int age;
    private final String email;
    private final String phone;
    private final String address;
    
    private Person(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.email = builder.email;
        this.phone = builder.phone;
        this.address = builder.address;
    }
    
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
    
    /**
     * 静态内部建造者类
     */
    public static class Builder {
        private String name;
        private int age;
        private String email;
        private String phone;
        private String address;
        
        public Builder name(String name) {
            this.name = name;
            return this;
        }
        
        public Builder age(int age) {
            this.age = age;
            return this;
        }
        
        public Builder email(String email) {
            this.email = email;
            return this;
        }
        
        public Builder phone(String phone) {
            this.phone = phone;
            return this;
        }
        
        public Builder address(String address) {
            this.address = address;
            return this;
        }
        
        public Person build() {
            // 可以在这里进行参数校验
            if (name == null || name.trim().isEmpty()) {
                throw new IllegalArgumentException("姓名不能为空");
            }
            return new Person(this);
        }
    }
}

/**
 * SQL建造者示例
 */
class SQLBuilder {
    private StringBuilder sql = new StringBuilder();
    
    public SQLBuilder select(String... columns) {
        sql.append("SELECT ");
        sql.append(String.join(", ", columns));
        return this;
    }
    
    public SQLBuilder from(String table) {
        sql.append(" FROM ").append(table);
        return this;
    }
    
    public SQLBuilder where(String condition) {
        sql.append(" WHERE ").append(condition);
        return this;
    }
    
    public SQLBuilder and(String condition) {
        sql.append(" AND ").append(condition);
        return this;
    }
    
    public SQLBuilder or(String condition) {
        sql.append(" OR ").append(condition);
        return this;
    }
    
    public SQLBuilder orderBy(String orderBy) {
        sql.append(" ORDER BY ").append(orderBy);
        return this;
    }
    
    public SQLBuilder limit(int limit) {
        sql.append(" LIMIT ").append(limit);
        return this;
    }
    
    public String build() {
        return sql.toString();
    }
}

// ==================== 原型模式实现 ====================

/**
 * 浅拷贝原型
 */
class ShallowPrototype implements Cloneable {
    private String name;
    private List<String> items;
    
    public ShallowPrototype(String name, List<String> items) {
        this.name = name;
        this.items = items;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 浅拷贝：只复制对象本身，不复制引用的对象
        return super.clone();
    }
    
    public List<String> getItems() {
        return items;
    }
    
    @Override
    public String toString() {
        return "ShallowPrototype{name='" + name + "', items=" + items + "}";
    }
}

/**
 * 深拷贝原型
 */
class DeepPrototype implements Cloneable {
    private String name;
    private List<String> items;
    
    public DeepPrototype(String name, List<String> items) {
        this.name = name;
        this.items = items;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 深拷贝：复制对象及其引用的所有对象
        DeepPrototype cloned = (DeepPrototype) super.clone();
        cloned.items = new ArrayList<>(this.items); // 复制列表
        return cloned;
    }
    
    public List<String> getItems() {
        return items;
    }
    
    @Override
    public String toString() {
        return "DeepPrototype{name='" + name + "', items=" + items + "}";
    }
}

/**
 * 用户原型类
 */
class UserPrototype implements Cloneable {
    private String name;
    private String email;
    
    public UserPrototype(String name, String email) {
        this.name = name;
        this.email = email;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    @Override
    public String toString() {
        return "UserPrototype{name='" + name + "', email='" + email + "'}";
    }
}

/**
 * 管理员原型类
 */
class AdminPrototype implements Cloneable {
    private String name;
    private String email;
    private String permissions;
    
    public AdminPrototype(String name, String email, String permissions) {
        this.name = name;
        this.email = email;
        this.permissions = permissions;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    @Override
    public String toString() {
        return "AdminPrototype{name='" + name + "', email='" + email + "', permissions='" + permissions + "'}";
    }
}

/**
 * 原型管理器
 */
class PrototypeManager {
    private Map<String, Cloneable> prototypes = new HashMap<>();
    
    public void addPrototype(String key, Cloneable prototype) {
        prototypes.put(key, prototype);
    }
    
    public Cloneable getPrototype(String key) throws CloneNotSupportedException {
        Cloneable prototype = prototypes.get(key);
        if (prototype == null) {
            throw new IllegalArgumentException("未找到原型：" + key);
        }
        
        // 使用反射调用clone方法
        try {
            return (Cloneable) prototype.getClass().getMethod("clone").invoke(prototype);
        } catch (Exception e) {
            throw new CloneNotSupportedException("克隆失败：" + e.getMessage());
        }
    }
}

// ==================== 适配器模式实现 ====================

/**
 * 高级媒体播放器接口
 */
interface AdvancedMediaPlayer {
    void playVlc(String fileName);
    void playMp4(String fileName);
}

/**
 * VLC播放器
 */
class VlcPlayer implements AdvancedMediaPlayer {
    @Override
    public void playVlc(String fileName) {
        System.out.println("播放VLC文件：" + fileName);
    }
    
    @Override
    public void playMp4(String fileName) {
        // VLC播放器不支持MP4
    }
}

/**
 * MP4播放器
 */
class Mp4Player implements AdvancedMediaPlayer {
    @Override
    public void playVlc(String fileName) {
        // MP4播放器不支持VLC
    }
    
    @Override
    public void playMp4(String fileName) {
        System.out.println("播放MP4文件：" + fileName);
    }
}

/**
 * 媒体播放器接口
 */
interface MediaPlayer {
    void play(String audioType, String fileName);
}

/**
 * 媒体适配器
 */
class MediaAdapter implements MediaPlayer {
    private AdvancedMediaPlayer advancedPlayer;
    
    public MediaAdapter(String audioType) {
        if ("vlc".equalsIgnoreCase(audioType)) {
            advancedPlayer = new VlcPlayer();
        } else if ("mp4".equalsIgnoreCase(audioType)) {
            advancedPlayer = new Mp4Player();
        }
    }
    
    @Override
    public void play(String audioType, String fileName) {
        if ("vlc".equalsIgnoreCase(audioType)) {
            advancedPlayer.playVlc(fileName);
        } else if ("mp4".equalsIgnoreCase(audioType)) {
            advancedPlayer.playMp4(fileName);
        }
    }
}

/**
 * 音频播放器
 */
class AudioPlayer implements MediaPlayer {
    private MediaAdapter mediaAdapter;
    
    @Override
    public void play(String audioType, String fileName) {
        // 内置支持MP3格式
        if ("mp3".equalsIgnoreCase(audioType)) {
            System.out.println("播放MP3文件：" + fileName);
        }
        // 通过适配器支持其他格式
        else if ("vlc".equalsIgnoreCase(audioType) || "mp4".equalsIgnoreCase(audioType)) {
            mediaAdapter = new MediaAdapter(audioType);
            mediaAdapter.play(audioType, fileName);
        } else {
            System.out.println("不支持的音频格式：" + audioType);
        }
    }
}

/**
 * 类适配器模式示例
 */
interface Target {
    void request();
}

class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee的特殊请求");
    }
}

class ClassAdapter extends Adaptee implements Target {
    @Override
    public void request() {
        System.out.println("ClassAdapter转换请求");
        specificRequest();
    }
}

// ==================== 装饰器模式实现 ====================

/**
 * 咖啡接口
 */
interface Coffee {
    String getDescription();
    double getCost();
}

/**
 * 简单咖啡
 */
class SimpleCoffee implements Coffee {
    @Override
    public String getDescription() {
        return "简单咖啡";
    }
    
    @Override
    public double getCost() {
        return 10.0;
    }
}

/**
 * 咖啡装饰器基类
 */
abstract class CoffeeDecorator implements Coffee {
    protected Coffee coffee;
    
    public CoffeeDecorator(Coffee coffee) {
        this.coffee = coffee;
    }
    
    @Override
    public String getDescription() {
        return coffee.getDescription();
    }
    
    @Override
    public double getCost() {
        return coffee.getCost();
    }
}

/**
 * 牛奶装饰器
 */
class MilkDecorator extends CoffeeDecorator {
    public MilkDecorator(Coffee coffee) {
        super(coffee);
    }
    
    @Override
    public String getDescription() {
        return coffee.getDescription() + ", 牛奶";
    }
    
    @Override
    public double getCost() {
        return coffee.getCost() + 2.0;
    }
}

/**
 * 糖装饰器
 */
class SugarDecorator extends CoffeeDecorator {
    public SugarDecorator(Coffee coffee) {
        super(coffee);
    }
    
    @Override
    public String getDescription() {
        return coffee.getDescription() + ", 糖";
    }
    
    @Override
    public double getCost() {
        return coffee.getCost() + 1.0;
    }
}

/**
 * 巧克力装饰器
 */
class ChocolateDecorator extends CoffeeDecorator {
    public ChocolateDecorator(Coffee coffee) {
        super(coffee);
    }
    
    @Override
    public String getDescription() {
        return coffee.getDescription() + ", 巧克力";
    }
    
    @Override
    public double getCost() {
        return coffee.getCost() + 3.0;
    }
}

// ==================== 代理模式实现 ====================

/**
 * 图片接口
 */
interface Image {
    void display();
}

/**
 * 真实图片类
 */
class RealImage implements Image {
    private String fileName;
    
    public RealImage(String fileName) {
        this.fileName = fileName;
        loadFromDisk();
    }
    
    private void loadFromDisk() {
        System.out.println("从磁盘加载图片：" + fileName);
        // 模拟耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    @Override
    public void display() {
        System.out.println("显示图片：" + fileName);
    }
}

/**
 * 图片代理类
 */
class ProxyImage implements Image {
    private String fileName;
    private RealImage realImage;
    
    public ProxyImage(String fileName) {
        this.fileName = fileName;
    }
    
    @Override
    public void display() {
        if (realImage == null) {
            realImage = new RealImage(fileName);
        }
        realImage.display();
    }
}

/**
 * 用户服务接口
 */
interface UserService {
    void login(String username, String password);
    void logout(String username);
}

/**
 * 真实用户服务
 */
class UserServiceImpl implements UserService {
    @Override
    public void login(String username, String password) {
        System.out.println("用户 " + username + " 登录成功");
    }
    
    @Override
    public void logout(String username) {
        System.out.println("用户 " + username + " 退出登录");
    }
}

/**
 * 服务调用处理器（动态代理）
 */
class ServiceInvocationHandler implements InvocationHandler {
    private Object target;
    
    public ServiceInvocationHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理执行前：记录日志 - 调用方法：" + method.getName());
        
        Object result = method.invoke(target, args);
        
        System.out.println("代理执行后：记录日志 - 方法执行完成");
        
        return result;
    }
}

// ==================== 外观模式实现 ====================

/**
 * 计算机子系统
 */
class CPU {
    public void start() {
        System.out.println("CPU启动");
    }
    
    public void shutdown() {
        System.out.println("CPU关闭");
    }
}

class Memory {
    public void load() {
        System.out.println("内存加载");
    }
    
    public void unload() {
        System.out.println("内存卸载");
    }
}

class HardDrive {
    public void read() {
        System.out.println("硬盘读取");
    }
    
    public void write() {
        System.out.println("硬盘写入");
    }
}

/**
 * 计算机外观
 */
class ComputerFacade {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;
    
    public ComputerFacade() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }
    
    public void start() {
        System.out.println("计算机启动中...");
        cpu.start();
        memory.load();
        hardDrive.read();
        System.out.println("计算机启动完成");
    }
    
    public void shutdown() {
        System.out.println("计算机关闭中...");
        hardDrive.write();
        memory.unload();
        cpu.shutdown();
        System.out.println("计算机已关闭");
    }
}

/**
 * 家庭影院子系统组件
 */
class Amplifier {
    public void on() {
        System.out.println("功放开启");
    }
    
    public void off() {
        System.out.println("功放关闭");
    }
    
    public void setVolume(int volume) {
        System.out.println("设置音量：" + volume);
    }
}

class DvdPlayer {
    public void on() {
        System.out.println("DVD播放器开启");
    }
    
    public void off() {
        System.out.println("DVD播放器关闭");
    }
    
    public void play(String movie) {
        System.out.println("播放电影：" + movie);
    }
    
    public void stop() {
        System.out.println("停止播放");
    }
}

class Projector {
    public void on() {
        System.out.println("投影仪开启");
    }
    
    public void off() {
        System.out.println("投影仪关闭");
    }
    
    public void wideScreenMode() {
        System.out.println("设置宽屏模式");
    }
}

class Screen {
    public void up() {
        System.out.println("屏幕升起");
    }
    
    public void down() {
        System.out.println("屏幕降下");
    }
}

class Lights {
    public void on() {
        System.out.println("灯光开启");
    }
    
    public void off() {
        System.out.println("灯光关闭");
    }
    
    public void dim(int level) {
        System.out.println("调暗灯光至：" + level + "%");
    }
}

/**
 * 家庭影院外观
 */
class HomeTheaterFacade {
    private Amplifier amp;
    private DvdPlayer dvd;
    private Projector projector;
    private Screen screen;
    private Lights lights;
    
    public HomeTheaterFacade() {
        this.amp = new Amplifier();
        this.dvd = new DvdPlayer();
        this.projector = new Projector();
        this.screen = new Screen();
        this.lights = new Lights();
    }
    
    public void watchMovie(String movie) {
        System.out.println("准备观看电影：" + movie);
        lights.dim(10);
        screen.down();
        projector.on();
        projector.wideScreenMode();
        amp.on();
        amp.setVolume(5);
        dvd.on();
        dvd.play(movie);
        System.out.println("电影开始播放");
    }
    
    public void endMovie() {
        System.out.println("关闭家庭影院");
        dvd.stop();
        dvd.off();
        amp.off();
        projector.off();
        screen.up();
        lights.on();
        System.out.println("家庭影院已关闭");
    }
}

// ==================== 观察者模式实现 ====================

/**
 * 观察者接口
 */
interface Observer {
    void update(String message);
}

/**
 * 主题接口
 */
interface Subject {
    void addObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

/**
 * 新闻机构（具体主题）
 */
class NewsAgency implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String news;
    
    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }
    
    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }
    
    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(news);
        }
    }
    
    public void setNews(String news) {
        this.news = news;
        System.out.println("发布新闻：" + news);
        notifyObservers();
    }
}

/**
 * 新闻频道（具体观察者）
 */
class NewsChannel implements Observer {
    private String name;
    
    public NewsChannel(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        System.out.println(name + " 收到新闻：" + message);
    }
}

/**
 * 股票价格主题
 */
class Stock implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String symbol;
    private double price;
    
    public Stock(String symbol, double price) {
        this.symbol = symbol;
        this.price = price;
    }
    
    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }
    
    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }
    
    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(symbol + " 价格更新为：$" + price);
        }
    }
    
    public void setPrice(double price) {
        this.price = price;
        System.out.println(symbol + " 价格更新为：$" + price);
        notifyObservers();
    }
}

/**
 * 股票投资者
 */
class Investor implements Observer {
    private String name;
    
    public Investor(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        System.out.println("投资者 " + name + " 收到通知：" + message);
    }
}

// ==================== 策略模式实现 ====================

/**
 * 折扣策略接口
 */
interface DiscountStrategy {
    double calculateDiscount(double originalPrice);
    String getDescription();
}

/**
 * 价格计算器类
 */
class PriceCalculator {
    private DiscountStrategy discountStrategy;
    
    public void setDiscountStrategy(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }
    
    public double calculatePrice(double originalPrice) {
        if (discountStrategy == null) {
            throw new IllegalStateException("折扣策略未设置");
        }
        return discountStrategy.calculateDiscount(originalPrice);
    }
    
    public String getCurrentStrategyDescription() {
        if (discountStrategy == null) {
            return "未设置折扣策略";
        }
        return discountStrategy.getDescription();
    }
}

/**
 * 普通客户折扣策略
 */
class RegularCustomerDiscount implements DiscountStrategy {
    private static final double DISCOUNT_RATE = 1.0;
    
    @Override
    public double calculateDiscount(double originalPrice) {
        return originalPrice * DISCOUNT_RATE;
    }
    
    @Override
    public String getDescription() {
        return "普通客户：无折扣";
    }
}

/**
 * VIP客户折扣策略
 */
class VIPCustomerDiscount implements DiscountStrategy {
    private static final double DISCOUNT_RATE = 0.9;
    
    @Override
    public double calculateDiscount(double originalPrice) {
        return originalPrice * DISCOUNT_RATE;
    }
    
    @Override
    public String getDescription() {
        return "VIP客户：9折优惠";
    }
}

/**
 * 超级VIP客户折扣策略
 */
class SuperVIPCustomerDiscount implements DiscountStrategy {
    private static final double DISCOUNT_RATE = 0.8;
    private static final double EXTRA_DISCOUNT_THRESHOLD = 1000.0;
    private static final double EXTRA_DISCOUNT_AMOUNT = 50.0;
    
    @Override
    public double calculateDiscount(double originalPrice) {
        double discountedPrice = originalPrice * DISCOUNT_RATE;
        
        // 满1000减50的额外优惠
        if (originalPrice >= EXTRA_DISCOUNT_THRESHOLD) {
            discountedPrice -= EXTRA_DISCOUNT_AMOUNT;
        }
        
        return Math.max(0, discountedPrice); // 确保价格不为负数
    }
    
    @Override
    public String getDescription() {
        return "超级VIP客户：8折优惠 + 满1000减50";
    }
}

/**
 * 商品类
 */
class Item {
    private String name;
    private int price;
    
    public Item(String name, int price) {
        this.name = name;
        this.price = price;
    }
    
    public String getName() {
        return name;
    }
    
    public int getPrice() {
        return price;
    }
}

/**
 * 支付策略接口
 */
interface PaymentStrategy {
    void pay(int amount);
}

/**
 * 信用卡支付策略
 */
class CreditCardStrategy implements PaymentStrategy {
    private String cardNumber;
    private String name;
    private String cvv;
    private String expiryDate;
    
    public CreditCardStrategy(String cardNumber, String name, String cvv, String expiryDate) {
        this.cardNumber = cardNumber;
        this.name = name;
        this.cvv = cvv;
        this.expiryDate = expiryDate;
    }
    
    @Override
    public void pay(int amount) {
        System.out.println("使用信用卡支付 $" + amount);
        System.out.println("卡号：" + cardNumber + "，持卡人：" + name);
    }
}

/**
 * PayPal支付策略
 */
class PayPalStrategy implements PaymentStrategy {
    private String email;
    private String password;
    
    public PayPalStrategy(String email, String password) {
        this.email = email;
        this.password = password;
    }
    
    @Override
    public void pay(int amount) {
        System.out.println("使用PayPal支付 $" + amount);
        System.out.println("账户：" + email);
    }
}

/**
 * 购物车上下文
 */
class ShoppingCart {
    private List<Item> items = new ArrayList<>();
    
    public void addItem(Item item) {
        items.add(item);
        System.out.println("添加商品：" + item.getName() + "，价格：$" + item.getPrice());
    }
    
    public void pay(PaymentStrategy paymentStrategy) {
        int totalAmount = items.stream().mapToInt(Item::getPrice).sum();
        System.out.println("\n结算购物车，总金额：$" + totalAmount);
        paymentStrategy.pay(totalAmount);
    }
}

/**
 * 排序策略接口
 */
interface SortStrategy {
    int[] sort(int[] array);
}

/**
 * 冒泡排序策略
 */
class BubbleSortStrategy implements SortStrategy {
    @Override
    public int[] sort(int[] array) {
        System.out.println("使用冒泡排序");
        int n = array.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        return array;
    }
}

/**
 * 快速排序策略
 */
class QuickSortStrategy implements SortStrategy {
    @Override
    public int[] sort(int[] array) {
        System.out.println("使用快速排序");
        quickSort(array, 0, array.length - 1);
        return array;
    }
    
    private void quickSort(int[] array, int low, int high) {
        if (low < high) {
            int pi = partition(array, low, high);
            quickSort(array, low, pi - 1);
            quickSort(array, pi + 1, high);
        }
    }
    
    private int partition(int[] array, int low, int high) {
        int pivot = array[high];
        int i = (low - 1);
        
        for (int j = low; j < high; j++) {
            if (array[j] <= pivot) {
                i++;
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
        
        int temp = array[i + 1];
        array[i + 1] = array[high];
        array[high] = temp;
        
        return i + 1;
    }
}

/**
 * 排序上下文
 */
class SortContext {
    private SortStrategy strategy;
    
    public void setSortStrategy(SortStrategy strategy) {
        this.strategy = strategy;
    }
    
    public int[] sort(int[] array) {
        if (strategy != null) {
            return strategy.sort(array);
        } else {
            System.out.println("请设置排序策略");
            return array;
        }
    }
}

// ==================== 模板方法模式实现 ====================

/**
 * 数据处理模板
 */
abstract class DataProcessor {
    
    /**
     * 模板方法：定义数据处理的算法骨架
     */
    public final void processData() {
        readData();
        if (needsValidation()) {
            validateData();
        }
        processBusinessLogic();
        saveData();
        if (needsNotification()) {
            sendNotification();
        }
    }
    
    /**
     * 抽象方法：子类必须实现
     */
    protected abstract void readData();
    protected abstract void processBusinessLogic();
    protected abstract void saveData();
    
    /**
     * 具体方法：提供默认实现
     */
    protected void validateData() {
        System.out.println("执行数据验证");
    }
    
    protected void sendNotification() {
        System.out.println("发送处理完成通知");
    }
    
    /**
     * 钩子方法：子类可以选择性重写
     */
    protected boolean needsValidation() {
        return true;
    }
    
    protected boolean needsNotification() {
        return false;
    }
}

/**
 * CSV数据处理器
 */
class CsvDataProcessor extends DataProcessor {
    
    @Override
    protected void readData() {
        System.out.println("从CSV文件读取数据");
    }
    
    @Override
    protected void processBusinessLogic() {
        System.out.println("处理CSV业务逻辑：数据清洗和转换");
    }
    
    @Override
    protected void saveData() {
        System.out.println("将处理后的数据保存到数据库");
    }
    
    @Override
    protected boolean needsNotification() {
        return true; // CSV处理完成后需要通知
    }
}

/**
 * XML数据处理器
 */
class XmlDataProcessor extends DataProcessor {
    
    @Override
    protected void readData() {
        System.out.println("从XML文件读取数据");
    }
    
    @Override
    protected void processBusinessLogic() {
        System.out.println("处理XML业务逻辑：解析XML结构");
    }
    
    @Override
    protected void saveData() {
        System.out.println("将XML数据保存到文件系统");
    }
    
    @Override
    protected void validateData() {
        System.out.println("执行XML Schema验证");
    }
    
    @Override
    protected boolean needsValidation() {
        return true;
    }
}

/**
 * JSON数据处理器
 */
class JsonDataProcessor extends DataProcessor {
    
    @Override
    protected void readData() {
        System.out.println("从JSON文件读取数据");
    }
    
    @Override
    protected void processBusinessLogic() {
        System.out.println("处理JSON业务逻辑：解析JSON对象");
    }
    
    @Override
    protected void saveData() {
        System.out.println("将JSON数据保存到NoSQL数据库");
    }
    
    @Override
    protected boolean needsValidation() {
        return false; // JSON数据不需要额外验证
    }
    
    @Override
    protected boolean needsNotification() {
        return true; // JSON处理完成后需要通知
    }
}

/**
 * 抽象饮料类
 */
abstract class Beverage {
    
    /**
     * 模板方法：定义制作饮料的算法骨架
     */
    public final void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        if (customerWantsCondiments()) {
            addCondiments();
        }
    }
    
    /**
     * 煮水 - 通用步骤
     */
    private void boilWater() {
        System.out.println("煮开水");
    }
    
    /**
     * 倒入杯中 - 通用步骤
     */
    private void pourInCup() {
        System.out.println("倒入杯中");
    }
    
    /**
     * 冲泡 - 抽象方法，由子类实现
     */
    protected abstract void brew();
    
    /**
     * 添加调料 - 抽象方法，由子类实现
     */
    protected abstract void addCondiments();
    
    /**
     * 钩子方法：客户是否需要调料
     */
    protected boolean customerWantsCondiments() {
        return true;
    }
}

/**
 * 茶类 - 具体实现
 */
class Tea extends Beverage {
    
    @Override
    protected void brew() {
        System.out.println("用沸水冲泡茶叶");
    }
    
    @Override
    protected void addCondiments() {
        System.out.println("加柠檬");
    }
}

/**
 * 咖啡饮料类 - 具体实现（模板方法模式）
 */
class CoffeeBeverage extends Beverage {
    
    @Override
    protected void brew() {
        System.out.println("用沸水冲泡咖啡");
    }
    
    @Override
    protected void addCondiments() {
        System.out.println("加糖和牛奶");
    }
}

/**
 * 抽象游戏类
 */
abstract class Game {
    
    /**
     * 模板方法：定义游戏流程
     */
    public final void play() {
        initialize();
        startPlay();
        endPlay();
    }
    
    /**
     * 初始化游戏 - 抽象方法
     */
    protected abstract void initialize();
    
    /**
     * 开始游戏 - 抽象方法
     */
    protected abstract void startPlay();
    
    /**
     * 结束游戏 - 抽象方法
     */
    protected abstract void endPlay();
}

/**
 * 足球游戏 - 具体实现
 */
class Football extends Game {
    
    @Override
    protected void initialize() {
        System.out.println("足球游戏初始化：设置球场，分配球员");
    }
    
    @Override
    protected void startPlay() {
        System.out.println("足球游戏开始：踢球中...");
    }
    
    @Override
    protected void endPlay() {
        System.out.println("足球游戏结束：统计比分");
    }
}

/**
 * 篮球游戏 - 具体实现
 */
class Basketball extends Game {
    
    @Override
    protected void initialize() {
        System.out.println("篮球游戏初始化：设置篮球场，分配球员");
    }
    
    @Override
    protected void startPlay() {
        System.out.println("篮球游戏开始：投篮中...");
    }
    
    @Override
    protected void endPlay() {
        System.out.println("篮球游戏结束：统计得分");
    }
}

// ==================== 责任链模式实现 ====================

/**
 * 抽象日志处理器
 */
abstract class Logger {
    // 日志级别常量
    public static final int INFO = 1;
    public static final int DEBUG = 2;
    public static final int ERROR = 3;
    
    protected int level;
    protected Logger nextLogger;
    
    /**
     * 设置下一个处理器
     */
    public void setNextLogger(Logger nextLogger) {
        this.nextLogger = nextLogger;
    }
    
    /**
     * 记录日志消息
     */
    public void logMessage(int level, String message) {
        if (this.level <= level) {
            write(message);
        }
        if (nextLogger != null) {
            nextLogger.logMessage(level, message);
        }
    }
    
    /**
     * 抽象方法：具体的日志写入实现
     */
    protected abstract void write(String message);
}

/**
 * 控制台日志处理器
 */
class ConsoleLogger extends Logger {
    
    public ConsoleLogger(int level) {
        this.level = level;
    }
    
    @Override
    protected void write(String message) {
        System.out.println("Console Logger: " + message);
    }
}

/**
 * 文件日志处理器
 */
class FileLogger extends Logger {
    
    public FileLogger(int level) {
        this.level = level;
    }
    
    @Override
    protected void write(String message) {
        System.out.println("File Logger: " + message);
    }
}

/**
 * 错误日志处理器
 */
class ErrorLogger extends Logger {
    
    public ErrorLogger(int level) {
        this.level = level;
    }
    
    @Override
    protected void write(String message) {
        System.err.println("Error Logger: " + message);
    }
}

/**
 * 采购请求类
 */
class PurchaseRequest {
    private String item;
    private double amount;
    
    public PurchaseRequest(String item, double amount) {
        this.item = item;
        this.amount = amount;
    }
    
    public String getItem() {
        return item;
    }
    
    public double getAmount() {
        return amount;
    }
}

/**
 * 抽象审批者
 */
abstract class Approver {
    protected Approver nextApprover;
    protected String name;
    
    public Approver(String name) {
        this.name = name;
    }
    
    public void setNextApprover(Approver nextApprover) {
        this.nextApprover = nextApprover;
    }
    
    public abstract void processRequest(PurchaseRequest request);
}

/**
 * 主管审批者
 */
class Supervisor extends Approver {
    private static final double LIMIT = 1000;
    
    public Supervisor() {
        super("主管");
    }
    
    @Override
    public void processRequest(PurchaseRequest request) {
        if (request.getAmount() <= LIMIT) {
            System.out.println(name + "审批通过：" + request.getItem() + "，金额：$" + request.getAmount());
        } else if (nextApprover != null) {
            System.out.println(name + "无权审批，转交给上级");
            nextApprover.processRequest(request);
        } else {
            System.out.println("没有合适的审批者");
        }
    }
}

/**
 * 经理审批者
 */
class PurchaseManager extends Approver {
    private static final double LIMIT = 10000;
    
    public PurchaseManager() {
        super("经理");
    }
    
    @Override
    public void processRequest(PurchaseRequest request) {
        if (request.getAmount() <= LIMIT) {
            System.out.println(name + "审批通过：" + request.getItem() + "，金额：$" + request.getAmount());
        } else if (nextApprover != null) {
            System.out.println(name + "无权审批，转交给上级");
            nextApprover.processRequest(request);
        } else {
            System.out.println("没有合适的审批者");
        }
    }
}

/**
 * 总监审批者
 */
class PurchaseDirector extends Approver {
    private static final double LIMIT = 50000;
    
    public PurchaseDirector() {
        super("总监");
    }
    
    @Override
    public void processRequest(PurchaseRequest request) {
        if (request.getAmount() <= LIMIT) {
            System.out.println(name + "审批通过：" + request.getItem() + "，金额：$" + request.getAmount());
        } else if (nextApprover != null) {
            System.out.println(name + "无权审批，转交给上级");
            nextApprover.processRequest(request);
        } else {
            System.out.println("没有合适的审批者");
        }
    }
}

/**
 * CEO审批者
 */
class CEO extends Approver {
    
    public CEO() {
        super("CEO");
    }
    
    @Override
    public void processRequest(PurchaseRequest request) {
        System.out.println(name + "审批通过：" + request.getItem() + "，金额：$" + request.getAmount());
    }
}

/**
 * 过滤器接口 - 责任链模式实现
 */
interface Filter {
    /**
     * 设置下一个过滤器
     * @param nextFilter 下一个过滤器
     */
    void setNext(Filter nextFilter);
    
    /**
     * 执行过滤操作
     * @param request HTTP请求
     */
    void doFilter(HttpRequest request);
    
    /**
     * 执行过滤操作（字符串版本，向后兼容）
     * @param request 请求字符串
     */
    void execute(String request);
}

/**
 * 抽象过滤器基类
 */
abstract class AbstractFilter implements Filter {
    protected Filter nextFilter;
    
    @Override
    public void setNext(Filter nextFilter) {
        this.nextFilter = nextFilter;
    }
    
    /**
     * 调用下一个过滤器
     * @param request HTTP请求
     */
    protected void callNext(HttpRequest request) {
        if (nextFilter != null) {
            nextFilter.doFilter(request);
        }
    }
}

/**
 * 过滤器链
 */
class FilterChain {
    private List<Filter> filters = new ArrayList<>();
    private int index = 0;
    
    public FilterChain addFilter(Filter filter) {
        filters.add(filter);
        return this;
    }
    
    public void execute(String request) {
        if (index < filters.size()) {
            Filter filter = filters.get(index++);
            filter.execute(request);
        }
    }
}

/**
 * 认证过滤器
 */
class AuthenticationFilter extends AbstractFilter {
    @Override
    public void doFilter(HttpRequest request) {
        System.out.println("认证过滤器：验证用户身份 - " + request.getUsername());
        
        // 简单的认证逻辑
        if ("admin".equals(request.getUsername()) && "admin".equals(request.getPassword())) {
            System.out.println("认证成功：管理员用户");
            callNext(request);
        } else if ("guest".equals(request.getUsername())) {
            System.out.println("认证成功：游客用户");
            callNext(request);
        } else {
            System.out.println("认证失败：用户名或密码错误");
        }
    }
    
    @Override
    public void execute(String request) {
        System.out.println("认证过滤器：验证用户身份 - " + request);
    }
}

/**
 * 授权过滤器
 */
class AuthorizationFilter extends AbstractFilter {
    @Override
    public void doFilter(HttpRequest request) {
        System.out.println("授权过滤器：检查用户权限 - " + request.getUrl());
        
        // 简单的授权逻辑
        if ("admin".equals(request.getUsername()) || request.getUrl().startsWith("/public")) {
            System.out.println("授权成功：允许访问 " + request.getUrl());
            callNext(request);
        } else {
            System.out.println("授权失败：权限不足，无法访问 " + request.getUrl());
        }
    }
    
    @Override
    public void execute(String request) {
        System.out.println("授权过滤器：检查用户权限 - " + request);
    }
}

/**
 * 日志过滤器
 */
class LoggingFilter extends AbstractFilter {
    @Override
    public void doFilter(HttpRequest request) {
        System.out.println("日志过滤器：记录请求日志 - " + request);
        System.out.println("访问时间：" + new java.util.Date());
        System.out.println("请求处理完成");
        callNext(request);
    }
    
    @Override
    public void execute(String request) {
        System.out.println("日志过滤器：记录请求日志 - " + request);
    }
}

// ==================== 流装饰器模式实现 ====================

/**
 * 数据流接口
 */
interface DataStream {
    void writeData(String data);
    String readData();
}

/**
 * 文件数据流
 */
class FileDataStream implements DataStream {
    private String filename;
    private String data = "";
    
    public FileDataStream(String filename) {
        this.filename = filename;
    }
    
    @Override
    public void writeData(String data) {
        this.data = data;
        System.out.println("写入文件 " + filename + ": " + data);
    }
    
    @Override
    public String readData() {
        System.out.println("从文件 " + filename + " 读取数据");
        return data;
    }
}

/**
 * 数据流装饰器基类
 */
abstract class DataStreamDecorator implements DataStream {
    protected DataStream wrappee;
    
    public DataStreamDecorator(DataStream source) {
        this.wrappee = source;
    }
    
    @Override
    public void writeData(String data) {
        wrappee.writeData(data);
    }
    
    @Override
    public String readData() {
        return wrappee.readData();
    }
}

/**
 * 加密装饰器
 */
class EncryptionDecorator extends DataStreamDecorator {
    
    public EncryptionDecorator(DataStream source) {
        super(source);
    }
    
    @Override
    public void writeData(String data) {
        String encryptedData = encrypt(data);
        System.out.println("加密数据: " + data + " -> " + encryptedData);
        super.writeData(encryptedData);
    }
    
    @Override
    public String readData() {
        String data = super.readData();
        String decryptedData = decrypt(data);
        System.out.println("解密数据: " + data + " -> " + decryptedData);
        return decryptedData;
    }
    
    private String encrypt(String data) {
        // 简单的加密算法（实际应用中应使用更安全的算法）
        return "encrypted(" + data + ")";
    }
    
    private String decrypt(String data) {
        // 简单的解密算法
        if (data.startsWith("encrypted(") && data.endsWith(")")) {
            return data.substring(10, data.length() - 1);
        }
        return data;
    }
}

/**
 * 压缩装饰器
 */
class CompressionDecorator extends DataStreamDecorator {
    
    public CompressionDecorator(DataStream source) {
        super(source);
    }
    
    @Override
    public void writeData(String data) {
        String compressedData = compress(data);
        System.out.println("压缩数据: " + data + " -> " + compressedData);
        super.writeData(compressedData);
    }
    
    @Override
    public String readData() {
        String data = super.readData();
        String decompressedData = decompress(data);
        System.out.println("解压数据: " + data + " -> " + decompressedData);
        return decompressedData;
    }
    
    private String compress(String data) {
        // 简单的压缩算法
        return "compressed(" + data + ")";
    }
    
    private String decompress(String data) {
        // 简单的解压算法
        if (data.startsWith("compressed(") && data.endsWith(")")) {
            return data.substring(11, data.length() - 1);
        }
        return data;
    }
}

// ==================== HTTP请求类 ====================

/**
 * HTTP请求类 - 用于过滤器链模式演示
 */
class HttpRequest {
    private String username;
    private String password;
    private String url;
    
    /**
     * 构造函数
     * @param username 用户名
     * @param password 密码
     * @param url 请求URL
     */
    public HttpRequest(String username, String password, String url) {
        this.username = username;
        this.password = password;
        this.url = url;
    }
    
    /**
     * 获取用户名
     * @return 用户名
     */
    public String getUsername() {
        return username;
    }
    
    /**
     * 获取密码
     * @return 密码
     */
    public String getPassword() {
        return password;
    }
    
    /**
     * 获取请求URL
     * @return 请求URL
     */
    public String getUrl() {
        return url;
    }
    
    @Override
    public String toString() {
        return "HttpRequest{username='" + username + "', url='" + url + "'}";
    }
}